<?php

declare(strict_types=1);

namespace app\api\controller;

use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\View;
use think\response\Json;
use app\common\model\Lntegral as ProductModel;
use app\common\model\User;
use app\common\model\LntegralSpecData;
use app\common\model\LntegralSpecValue;
use app\common\model\Account;
use app\common\model\Order;
use app\common\controller\Config;
use app\common\model\LntegralCate;
use app\common\model\Carousel;
use app\common\tool\Result;


class Lntegral extends Base
{

    /**
     * 积分商城
     */
    public function index()
    {
        try {
            $money = 0.00;
            $token = $this->request->header('token');
            if (!empty($token)) {
                $user = User::where(['token' => $token, 'is_del' => 0])->find();
                if (!empty($user)) {
                    $money = $user->assets->lntegral;
                }
            }
            $data['money'] = $money;
            $data['banner'] = Carousel::getList(['type' => 4], true, 'sort', [], 'id,images,link,details_image');
            $data['cate'] = LntegralCate::where(['is_del' => 0, 'status' => 1])->field('id,title')->order('sort asc')->select();
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /***
     * 积分商城列表
     */
    public function getList()
    {
        try {
            $param = $this->request->param();
            $map[] = ['is_del', '=', 0];
            $map[] = ['status', '=', 1];
            $key = 'create_time';
            $value = 'desc';
            //分类id
            if (isset($param['cate_1']) && $param['cate_1']) {
                $map[] = ['cate_1', '=', $param['cate_1']];
            } else {
                $map[] = ['pick', '=', 1];
            }
            //类型
            if (isset($param['cate']) && $param['cate']) {
                if ($param['cate'] == 1) {
                    $key = "price"; //价格平排序
                } else {
                    $key = 'create_time'; //默认排序
                }
            }
            //排序类型
            if (isset($param['types']) && $param['types']) {
                $value = $param['types'];
            }
            $sort = ['key' => $key, 'value' => $value];
            $list = ProductModel::getPageList($map, 'id,title,price,icon', $param['page'], 20, false, '', '', $sort);
            return Result::success('获取成功！', $list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 商品详情
     */
    public function details($id)
    {
        try {
            $info = ProductModel::where(['status' => 1, 'is_del' => 0, 'id' => $id])
                ->field('id,title,describe,price,icon,stock,sales,content_text,content_images,images')->find();
            if (empty($info)) return json(['code' => -1, 'msg' => '商品不存在或已下架']);
            $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $info->content_text = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content_text));
            $info->content_text = str_replace('\\', '', $info->content_text);

            $product_spec = LntegralSpecData::where(['pid' => $id])->order('id asc')->select();
            foreach ($product_spec as $k => $v) {
                $clist = json_decode($v['child'], true);
                foreach ($clist as $kk => $vv) {
                    $clist[$kk]['check'] = 0;
                }
                $v['list'] = $clist;
                $product_spec[$k] = $v;
            }
            $info['product_spec'] = $product_spec;
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取规格信息
     */
    public function getProductSpec()
    {
        $param = $this->request->param();
        try {
            $data = LntegralSpecValue::where(['pid' => $param['pid'], 'sku_id' => $param['sku_id']])->find();
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 商品提交
     * */
    public function submit()
    {
        $param = $this->request->post();
        try {
            $result = ProductModel::submit($param, $this->user);
            $result['code'] = $result['code'] >= 1 ? 1 : -1;
            return json($result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /***
     * 获取订单信息
     ***/
    public function orderInfo()
    {
        try {
            $temporary = Order::getLntegralTemporary($this->user->id);
            if (empty($temporary) || empty($temporary['products'])) {
                return Result::fail('加载失败，未查询到待提交的订单', '', -6);
            }
            return Result::success('获取成功！', $temporary);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 提交订单
     */
    public function orderSubmit()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(Order::orderSubmit($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取收银信息
     */
    public function payment()
    {
        try {
            $buy_bs = Config::lists()['buy_bs'];
            $info = Order::getNowLntegralOrder($this->user);
            if ($info['code'] != 1) {
                return Result::fail('加载失败，未查询到待支付的订单', '', -6);
            }
            $user_lntegral = $this->user->assets->lntegral;
            $real_amount = $info['result']['real_amount'];
            if (($user_lntegral - $real_amount) >= 0) {
                $key = 'lntegral';
                $title = '积分支付';
            } else {
                $key = 'group_pay';
                $title = '现金+积分支付';
            }
            $data['money'] = $info['result']['money'];
            $data['lntegral'] = $info['result']['lntegral'];
            $data['order_id'] = $info['result']['id'];
            $data['method'] = [
                [
                    'title' => $title,
                    'pay_way' => $key,
                ]
            ];
            return Result::success('获取成功！',  $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 提交订单
     */
    public function confirmPayment(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'ConfirmPayment');
            return Result::fastReturn(Order::confirmlLntegralPayment($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取积分记录
     */
    public function getLntegralLog()
    {
        try {
            $param = $this->request->param();
            $map[] = ['uid', '=', $this->user->id];
            $map[] = ['type', '=', 'lntegral'];
            $list = Account::getPageList($map, '*', $param['page'], 20, false, '', '', '');
            return Result::success('获取成功！', $list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
